package com.huyn.baseframework.share;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.android.volley.Response;
import com.huyn.baseframework.model.WXLoginModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.Utils;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.HashMap;

/**
 * Created by huyaonan on 16/7/1.
 */
public class WxUtil {

    public static void wxLoginRequest(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo packageInfo = manager.getPackageInfo("com.tencent.mm", 0);
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            boolean enabled = applicationInfo.enabled;
            if (!enabled) {
                Utils.showToast(context, "您未安装最新版微信！");
                return;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "none";
        req.openId = Constant.APP_ID;

        IWXAPI wxApi = WXAPIFactory.createWXAPI(context, Constant.APP_ID, false);
        wxApi.registerApp(Constant.APP_ID);
        if (wxApi.isWXAppInstalled()) {
            boolean result = wxApi.sendReq(req);
        } else {
            Utils.showToast(context, "您未安装最新版微信！");
        }
    }

    /**
     * 微信登录并保留凭证
     * @param code
     */
    public static void doWechatLogin(Context context, String code, Response.Listener<WXLoginModel> listener) {
        HashMap<String, String> parameterMap = new HashMap<>();
        parameterMap.put("code", code);
        parameterMap.put(OpenApi.API_METHOD, OpenApi.WX_LOGIN);
        BFJSONRequest request = new BFJSONRequest(WXLoginModel.class, parameterMap, listener);
        HttpRequestLoader.getInstance(context).startCacheLoader("", request, true);
    }

}
